<?php
// 请假系统

!defined('IN_SYSTEM') && exit('Access denied');

class vacationControlPage extends commonControlPage 
{
	/* 
	 * 提交请假申请
	*/
    public function postModule()
	{
		if (POST && AJAX) 
		{
			$mark = htmlspecialchars($_POST['mark']);
			$date = $this->checkDateFormatPost();   //验证并格式化请假开始和结束日期
			$next_uid = $_POST['next_uid'];
            if (!class_permission::ValidateNodeByUser($_ENV['config']['vacation_audit_nodes'][0],$next_uid)) 
			{
                $this->outputJson(0,'指定的操作员无权限');
            }
			$param = array();
			$param['start_date'] = $date['s'];
			$param['end_date']   = $date['e'];
			$param['uid']        = $this->user['uid'];
			$param['username']   = $this->user['username'];
			$param['nickname']   = $this->user['nickname'];
			$param['mark']       = $mark;
			$param['created_time'] = $_ENV['time'];
            $param['co_member_id'] = $next_uid;
			$_ENV['db']->runSql("INSERT INTO `vacation` ".$this->buildSql($param));
			$this->outputJson(1,'请假单已提交审核，请耐心等待');
		}
		$this->view->addScript('rili');
		$this->view->users = class_permission::GetUsersByNodeID($_ENV['config']['vacation_audit_nodes'][0]);
        $this->showMainPage('admincp/vacation_post');
    }

	/*请假单列表*/
	public function listModule() {
		if (preg_match('/[0-9]+/',$_GET['vacation_id'])) 
		{
			$vacation = $_ENV['db']->fetch("SELECT * FROM `vacation` WHERE `vacation_id` = '{$_GET['vacation_id']}'");
			$this->view->orderState = $this->GetOrderStatus($vacation['audit_state']);
			if($vacation['uid'])
			{
				$userdetail = $_ENV['db']->fetch("SELECT * FROM `admincp_member_detail` WHERE `uid` = '{$vacation['uid']}'");
				$vacation['total_vacation']    = $userdetail['total_vacation'];
				$vacation['statutory_holiday'] = $userdetail['statutory_holiday'];
				$vacation['sum_vacation']      =$userdetail['sum_vacation'];
			}
			$this->view->vacation = $vacation;
			$this->showMainPage('admincp/vacation_desc');
		} 
		else 
		{
			$this->doVacationList();
			$this->showMainPage('admincp/vacation_list');
		}
	}
	/* 
	* 我的请假单
	*/
    public function myModule() 
	{
        if (!empty($_GET['vacation_id'])) 
		{
            $vacation = $_ENV['db']->fetch("SELECT * FROM vacation WHERE vacation_id = '".$_GET['vacation_id']."'");
			$this->view->orderState = $this->GetOrderStatus($vacation['audit_state']);
			if($vacation['uid'])
			{
				$userdetail = $_ENV['db']->fetch("SELECT * FROM `admincp_member_detail` WHERE `uid` = '{$vacation['uid']}'");
				$vacation['total_vacation']    = $userdetail['total_vacation'];
				$vacation['statutory_holiday'] = $userdetail['statutory_holiday'];
				$vacation['sum_vacation']      =$userdetail['sum_vacation'];
			}
            $this->view->vacation = $vacation;
            $this->showMainPage('admincp/vacation_desc');
        } 
		else 
		{
			//日期选择控件JS
			$this->view->addScript('rili');
			$page = (int)$_GET['page_no'];
			$_GET['page_no'] = 'TPT';
				
			$type = $_GET['type']? $_GET['type']:'m';
			
			if($type=='m')
			{  //我的欠款记录
				$where = ' 1 and uid="'.$this->user['uid'].'" ';
				if($_GET['start_date'] && $_GET['end_date'])
				{
					$date = $this->checkDateFormat();
					$start_date = $date['s'];
					$end_date   = $date['e'];
					$where .= ' and created_time between '.$start_date.' and '.$end_date;
				}
				$this->view->maction = ' class="active" ';
			}
			else if($type=='s')
			{
				$where = '1 and audit1_uid="'.$this->user['uid'].'" ';
				if($_GET['start_date'] && $_GET['end_date'])
				{
					$date = $this->checkDateFormat();
					$start_date = $date['s'];
					$end_date   = $date['e'];
					$where .= ' and created_time between '.$start_date.' and '.$end_date;
				}
				$this->view->saction = ' class="active" ';
			}
			else if($type=='f')
			{
				$where = '1 and audit2_uid="'.$this->user['uid'].'" ';
				if($_GET['start_date'] && $_GET['end_date'])
				{
					$date = $this->checkDateFormat();
					$start_date = $date['s'];
					$end_date   = $date['e'];
					$where .= ' and created_time between '.$start_date.' and '.$end_date;
				}
				$this->view->faction = ' class="active" ';
			}
			
			$list =  $this->PrePage('vacation','vacation_id',$where,$page,'vacation_id desc');
			foreach((array)$list as $key=>$value)
			{
				$list[$key]['audit_state'] = $this->GetOrderStatus($value['audit_state']);
			}
			$this->view->vacation_list = $list;
			$this->view->type = $type;
            $this->showMainPage('admincp/vacation_mylist');
        }
    }
	
	/* 
	* 魔法方法实现审批流程
	*/
    public function __call($func,$args) 
	{
        if(substr($func,0,5) == 'audit' && substr($func,5,1) > 0 && substr($func,5,1) < 3) 
		{   //audit1 和 audit2
            $step = substr($func,5,1);
			if (preg_match('/[0-9]+/',$_GET['vacation_id'])) 
			{
				$vacation = $_ENV['db']->fetch("SELECT * FROM `vacation` WHERE `vacation_id` = '{$_GET['vacation_id']}'");
				if (!$vacation) $this->showMessage('指定的请假单不存在',AJAX?0:'back');
				$node_id = $_ENV['config']['vacation_audit_nodes'][$step];
				if (POST && AJAX) 
				{
					$param = array();
					$param['audit_state'] = $step + 1;       //审核状态
					$next_uid = (int)$_POST['next_uid'];     //下级审核人
					$param['co_member_id'] = $next_uid;
					switch($step) 
					{
						case '1':
							$param['audit1_uid'] = $this->user['uid'];
							$param['audit1_username'] = $this->user['username'];
							$param['audit1_dateline'] = $_ENV['time'];
						break;
						case '2':
							$param['audit2_uid'] = $this->user['uid'];
							$param['audit2_username'] = $this->user['username'];
							$param['audit2_dateline'] = $_ENV['time'];
						break;
					}
					if ($step==1) 
					{   # 如果是审核1，需要验证下级操作员
						if (!class_permission::ValidateNodeByUser($node_id,$next_uid)) $this->outputJson(0,'指定的下级操作员没有足够的权限');
					}
					else
					{  //请假单复审，更新用户的假期总天数
						$days=round(($vacation['end_date']-$vacation['start_date'])/3600/24) + 1 ;
						$_ENV['db']->runSql("update `admincp_member_detail` SET `total_vacation` = total_vacation + {$days},sum_vacation=sum_vacation+1 where uid= '{$this->user['uid']}'");
					}
					$_ENV['db']->runSql("UPDATE `vacation` ".$this->buildSql($param)." WHERE `vacation_id` = '{$_GET['vacation_id']}'");
					$this->outputJson(1,'操作成功');
				}

				if($vacation['uid'])
				{
					$userdetail = $_ENV['db']->fetch("SELECT * FROM `admincp_member_detail` WHERE `uid` = '{$vacation['uid']}'");
					$vacation['total_vacation']    = $userdetail['total_vacation'];
					$vacation['statutory_holiday'] = $userdetail['statutory_holiday'];
					$vacation['sum_vacation']      =$userdetail['sum_vacation'];
				}
				
				switch ($step) {
					case '1':
						$operation = '<input type="submit" value="审核通过，转二级审核"/>';
					break;
					case '2':
						$operation = '<input type="submit" value="审核通过"/>';
					break;
				}
				$this->view->orderState = $this->GetOrderStatus($vacation['audit_state']);
				$this->view->operation = $operation;
				$this->view->next_user_list = class_permission::GetUsersByNodeID($node_id);  // 获取下级操作员列表
				$this->view->step     = $step;
				$this->view->vacation = $vacation;
				$this->showMainPage('admincp/vacation_desc');
			} else {
				$this->doVacationList($step);
			    $this->showMainPage('admincp/vacation_list');
			}
        } else {
            parent::__call($func,$args);
        }
    }

	//不允许请假
	public function notallowModule()
	{
		if (AJAX) 
		{
			$vid = $_GET['vid'];
			$step = $_GET['step'];
			switch($step) 
			{
				case '1':
					$param['audit1_uid'] = $this->user['uid'];
					$param['audit1_username'] = $this->user['username'];
					$param['audit1_dateline'] = $_ENV['time'];
					break;
				case '2':
					$param['audit2_uid'] = $this->user['uid'];
					$param['audit2_username'] = $this->user['username'];
					$param['audit2_dateline'] = $_ENV['time'];
					break;
			}
			$param['audit_state'] = '4';   //状态是不允许请假
			$_ENV['db']->runSql("UPDATE `vacation` ".$this->buildSql($param)." WHERE `vacation_id` = '{$vid}'");
			$this->outputJson(1,'操作成功');
		}
	}

	/*填写旷工天数*/
	public function neglectdayModule()
	{
		if (AJAX) 
		{
			$vid = $_GET['vid'];
			$day = $_GET['day'];
			if ($day && !preg_match('/\d{0,6}/',$day)) 
			{
            	$this->outputJson(0,'旷工天数为最多6位纯数字，不能有其它符号','tel');
        	}
			$param['neglect_day'] = $day;   // 请假天数
			UpdateTable('vacation',$param,array('vacation_id'=>$vid));
			$this->outputJson(1,'操作成功');
		}
	}

	/*销假*/
	public function lapseModule()
	{
		if (AJAX) 
		{
			$vacationID = $_GET['vid'];
			$lapse_date = $_GET['start_date'];
			if(!$vacationID) $this->showMessage('指定的请假单不存在',AJAX?0:'back');
			$vacation = $_ENV['db']->fetch("SELECT * FROM `vacation` WHERE `vacation_id` = '{$vacationID}'");
			if (!ValidateDate($lapse_date)) 
			{
            	$this->showMessage('日期格式错误','back');
        	}
			 $start_date = $vacation['start_date'];
			 $end_date   = $vacation['end_date'];
       		 $lapse_date = strtotime($lapse_date);
			 if($start_date>=$lapse_date)
			 {
				 $this->showMessage('销假日期要大于开始日期','back');
			 }
			 if($end_date<=$lapse_date)
			 {
				 $this->showMessage('销假日期要小于结束日期','back');
			 }
			 $param['lapse_date'] =  $lapse_date ;
			 $param['audit_state'] =  '5' ;
			UpdateTable('vacation',$param,array('vacation_id'=>$vacationID));
			$this->outputJson(1,'请假单已提交审核，请耐心等待'. $start_date);
		}
		
		$this->view->addScript('rili');
		$this->view->start_date = date('Y-m-d');
		
		if (preg_match('/[0-9]+/',$_GET['vacation_id'])) 
		{
			$vacation = $_ENV['db']->fetch("SELECT * FROM `vacation` WHERE `vacation_id` = '{$_GET['vacation_id']}'");
			$this->view->orderState = $this->GetOrderStatus($vacation['audit_state']);
			if($vacation['uid'])
			{
				$userdetail = $_ENV['db']->fetch("SELECT * FROM `admincp_member_detail` WHERE `uid` = '{$vacation['uid']}'");
				$vacation['total_vacation']    = $userdetail['total_vacation'];
				$vacation['statutory_holiday'] = $userdetail['statutory_holiday'];
				$vacation['sum_vacation']      =$userdetail['sum_vacation'];
			}
			$this->view->vacation = $vacation;
			$this->showMainPage('admincp/vacation_lapse');
		} 
	}
	
	/*销假审核列表*/
	public function lapseaudidModule()
	{
		if (AJAX) 
		{
			$vacationID = $_GET['vid'];
			if(!$vacationID) $this->showMessage('指定的请假单不存在',AJAX?0:'back');
			$vacation = $_ENV['db']->fetch("SELECT * FROM `vacation` WHERE `vacation_id` = '{$vacationID}'");
			$param['end_date'] =  $vacation['lapse_date'] ;
			$param['audit_state']  = '3';
			UpdateTable('vacation',$param,array('vacation_id'=>$vacationID));
			$days = round(($vacation['end_date']-$vacation['start_date'])/3600/24) + 1 ;//销假天数
			$chazhi = round(($vacation['end_date']-$vacation['lapse_date'])/3600/24)   ;//少请了几天数假
			$_ENV['db']->runSql("update `admincp_member_detail` SET `total_lapse` = total_lapse + {$days},sum_vacation=sum_vacation-{$chazhi},sum_lapse=sum_lapse+1 where uid= '{$vacation['uid']}'");
			$this->outputJson(1,'请假单已提交审核，请耐心等待'. $start_date);
		}
		if (preg_match('/[0-9]+/',$_GET['vacation_id'])) 
		{
			$vacation = $_ENV['db']->fetch("SELECT * FROM `vacation` WHERE `vacation_id` = '{$_GET['vacation_id']}'");
			$this->view->orderState = $this->GetOrderStatus($vacation['audit_state']);
			if($vacation['uid'])
			{
				$userdetail = $_ENV['db']->fetch("SELECT * FROM `admincp_member_detail` WHERE `uid` = '{$vacation['uid']}'");
				$vacation['total_vacation']    = $userdetail['total_vacation'];
				$vacation['statutory_holiday'] = $userdetail['statutory_holiday'];
				$vacation['sum_vacation']      =$userdetail['sum_vacation'];
			}
			$this->view->vacation = $vacation;
			$this->showMainPage('admincp/vacation_lapseaudid');
		} 
		else 
		{
			$this->doVacationList('5');
			$this->showMainPage('admincp/vacation_lapselist');
		}
	}
	
	/*不允许请假列表*/
	public function nolistModule()
	{
		if (preg_match('/[0-9]+/',$_GET['vacation_id'])) 
		{
			$vacation = $_ENV['db']->fetch("SELECT * FROM `vacation` WHERE `vacation_id` = '{$_GET['vacation_id']}'");
			$this->view->orderState = $this->GetOrderStatus($vacation['audit_state']);
			if($vacation['uid'])
			{
				$userdetail = $_ENV['db']->fetch("SELECT * FROM `admincp_member_detail` WHERE `uid` = '{$vacation['uid']}'");
				$vacation['total_vacation']    = $userdetail['total_vacation'];
				$vacation['statutory_holiday'] = $userdetail['statutory_holiday'];
				$vacation['sum_vacation']      =$userdetail['sum_vacation'];
			}
			$this->view->vacation = $vacation;
			$this->showMainPage('admincp/vacation_nodesc');
		} 
		else 
		{
			$this->doVacationList('4');    //不批准假单
			$this->showMainPage('admincp/vacation_nolist');
		}
	}
	

	//获得请假单状态
	private function GetOrderStatus($code)
	{
		switch($code)
		{
			case '1':  return '<span style="color:blue; font-size:14px;">未审批</span>';  break;
			case '2':  return '<span style="color:blue; font-size:14px;">未复审</span>';  break;
			case '3':  return '<span style="color:green; font-size:14px;">批准</span>';  break;
			case '4':  return '<span style="color:red; font-size:14px;">不批准</span>';  break;
			case '5':  return '<span style="color:red; font-size:14px;">销假未审批</span>';  break;
		}
		return '未审批';
	}
	

	public function call($method) 
	{
		$allowed = array('doVacationList');
		if (in_array($method,$allowed)) {
			call_user_func(array($this,$method));
		}
	}

	/* 
	* 根据查询条件查询请假信息
	*/
	private function doVacationList($audit_state='') 
	{	
		//日期选择控件JS
		$this->view->addScript('rili');
		$where = '1';
		$page = (int)$_GET['page_no'];
		$_GET['page_no'] = 'TPT';
		if($_GET['start_date'] && $_GET['end_date'])
		{
			$date = $this->checkDateFormat();
			$start_date = $date['s'];
			$end_date = $date['e'];
			$where .= ' and created_time between '.$start_date.' and '.$end_date;
		}
		// marge get
		if (!empty($_GET['searchtype']) && $_GET['keyword']) {
			//
			switch ($_GET['searchtype']) {
				case '1':
					//
				break;
			}
		}
		if ($audit_state) {
			$where .= ' and `audit_state` = '.$audit_state;
		}
        if ($this->user['uid'] && !in_array($this->user['uid'],$_ENV['config']['superadmin'])) {
            $where .= ' and `co_member_id` = '.$this->user['uid'] ;
        }
		$this->view->vacation_list = $this->PrePage('vacation','vacation_id',$where,$page,'vacation_id desc');
	}
	
	/* 用于POST提交的时间验证
	 * (1) 起始日期必须大于当前日期
	 * (2) 结束日期不得早于起始日期
	*/
	private function checkDateFormatPost() 
	{
        $start_date = $_POST['start_date'];
        $end_date   = $_POST['end_date'];
		$this->view->start_date = $start_date; //开始时间
		$this->view->end_date = $end_date;     //结束时间
        if (!ValidateDate($start_date)) {
			$this->outputJson(0,'起始时间不正确');
		}
		if (!ValidateDate($start_date)) {
			$this->outputJson(0,'结束时间不正确');
		}
		$start_date = strtotime($start_date);
        $end_date  = strtotime($end_date);
		
        if (date('Ymd',$start_date) < date('Ymd',$_ENV['time'])) {
			$this->outputJson(0,'起始日期必须大于当前日期');
		}
		if (date('Ymd',$end_date) < date('Ymd',$start_date)) {
			$this->outputJson(0,'结束日期不得早于起始日期');
		}
        return array('s'=>$start_date,'e'=>$end_date);
    }
	
	//验证时间格式
	/* 用于查询的时间验证
	 * (1) 结束时间必须小于开始时间
	 * (2) 所选日期时间段不能超过1年
	*/
	private function checkDateFormat() 
	{
        $start_date = $_GET['start_date'];
        $end_date = $_GET['end_date'];
		$this->view->start_date = $start_date;   //开始时间
		$this->view->end_date = $end_date;       //结束时间
        if (!ValidateDate($start_date) || !ValidateDate($end_date)) {
            $this->showMessage('日期格式错误','back');
        }
        $start_date = strtotime($start_date);
        $end_date = strtotime($end_date." 23:59:59");
        if ($start_date > $end_date) {
            $this->showMessage('结束时间必须小于开始时间','back');
        }
        if (($end_date-$start_date) > 31536000) {
            $this->showMessage('所选日期时间段超过了1年','back');
        }
        return array('s'=>$start_date,'e'=>$end_date);
    }
	
	
	public function reportModule()
	{
		//日期选择控件JS
		$this->view->addScript('rili');
        $this->view->addScript('autocomplete');
		$where = " 1 ";
		 $sel_UName = $_GET['searchUser'];       //查询人名称	
		//$sel_phase = $_GET['searchPhase'];    //项目阶段
		//$sel_Item = $_GET['searchItem'];      //选择项目
		if ($sel_UName ) 
		{   //通过用户名获得用户ID （UID）
			$sel_UID = $_ENV['db']->fetchCol("SELECT m.uid FROM `admincp_member` as m where username='". $sel_UName ."'");
        	$where .= ' and `uid` = '.$sel_UID;
       	}
		if($_GET['start_date'] && $_GET['end_date'])
		{
			$date = $this->checkDateFormat();
			$start_date = $date['s'];
			$end_date = $date['e'];
			$where .= ' and created_time between '.$start_date.' and '.$end_date;
		}
		$vacation = $_ENV['db']->fetchAll("SELECT * FROM `vacation` WHERE {$where} order by created_time asc,vacation_id desc");
	
		$result = array();
		foreach ((array)$vacation as $key=>$val) 
		{
			$days=round(($val['end_date']-$val['start_date'])/3600/24) + 1 ;  
			$val['sum_qingjia'] = $days;
			$result[$val['uid']]['items'][] = $val;
			$result[$val['uid']]['total'] += $days;
			$result[$val['uid']]['total_kuanggong'] += $val['neglect_day'];
			$result[$val['uid']]['nickname'] = $val['nickname'];
		}
	
		$this->view->result = $result;
		$this->view->sel_UName = $sel_UName;
		$this->showMainPage('admincp/vacation_report');
	}
}